package com.example.gyk.neteaseanimation.animation;

import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.app.Activity;
import android.content.Context;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;


import com.example.gyk.neteaseanimation.R;

import java.util.ArrayList;
import java.util.List;

/**
 * 项目名：JetpackPractice
 * 包名：com.example.gyk.jetpackpractice.animation
 * 文件名：SlideTheCard
 * 创建者：Gyk
 * 创建时间：2021/8/10 15:35
 * 描述：  TODO
 */

public class SlideTheCard extends RelativeLayout {
    private final String TAG = "SlideTheCardView";
    private Context mContext;
    private WindowManager wm;
    private int mScreenWidth;
    private int mScreenHeight;
    private boolean isRight = false;//手指移动方向
    private float mRotationAngle = 0;//旋转角度
    private float mInitX = 0;//初始化坐标
    private List<CardView> list = new ArrayList<>();//view 的集合
    private int position = 0;//当前view的在List的位置
    private final int MINTOUCHVALUE = 500;//滑动出屏幕时手指最小移动范围
    private final int ANIMATORDURATION = 300;//回弹动画时间

    public SlideTheCard(Context context) {
        this(context, null);
        this.mContext = context;
    }

    public SlideTheCard(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
        this.mContext = context;
    }

    public SlideTheCard(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.mContext = context;
        initView();
    }

    /**
     * 确定子View的位置
     *
     * @param changed
     * @param l
     * @param t
     * @param r
     * @param b
     */

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        super.onLayout(changed, l, t, r, b);
        int top = 0;
        for (int i = 0; i < list.size(); i++) {
            View vChild = getChildAt(i);
            int left = (mScreenWidth - list.get(i).getWidth()) / 2;
            if (i == list.size() - 2) {
                top = (list.get(i).getHeight() / 2 - 60);
            } else if (i == list.size() - 1) {
                top = (list.get(i).getHeight() / 2 - 120);
            } else {
                top = (list.get(i).getHeight() / 2);
            }
            int right = list.get(i).getWidth() + left;
            int bottom = list.get(i).getHeight() + top;
            vChild.setLeft(left);
            vChild.setTop(top);
            vChild.setRight(right);
            vChild.setBottom(bottom);
        }
    }


    private void initView() {
        wm = ((Activity) mContext).getWindowManager();
        DisplayMetrics outMetrics = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(outMetrics);
        mScreenWidth = outMetrics.widthPixels;
        mScreenHeight = outMetrics.heightPixels;
        Log.e(TAG, "mScreenWidth===" + mScreenWidth);
        Log.e(TAG, "mScreenHeight===" + mScreenHeight);


        CardView cardView = new CardView();
        cardView.setSlide(false);
        cardView.setFinishSlide(false);
        cardView.setWidth(DisplayUtil.dip2px(mContext, 260));
        cardView.setHeight(DisplayUtil.dip2px(mContext, 260));
        cardView.setMultiple(1f);
        cardView.setImageView(createImageView(DisplayUtil.dip2px(mContext, 260), DisplayUtil.dip2px(mContext, 260),"If you call me,我会用跑的，来到你的身边","-来自Gyk的评论-"));
        list.add(cardView);


        CardView cardView3 = new CardView();
        cardView3.setSlide(false);
        cardView3.setFinishSlide(false);
        cardView3.setWidth(DisplayUtil.dip2px(mContext, 260));
        cardView3.setHeight(DisplayUtil.dip2px(mContext, 260));
        cardView3.setMultiple(1f);
        cardView3.setImageView(createImageView(DisplayUtil.dip2px(mContext, 260), DisplayUtil.dip2px(mContext, 260),"希望你能为我停下，听我对你说的情话","-来自Gyk的评论-"));
        list.add(cardView3);


        CardView cardView5 = new CardView();
        cardView5.setSlide(false);
        cardView5.setFinishSlide(false);
        cardView5.setWidth(DisplayUtil.dip2px(mContext, 260));
        cardView5.setHeight(DisplayUtil.dip2px(mContext, 260));
        cardView5.setMultiple(1f);
        cardView5.setImageView(createImageView(DisplayUtil.dip2px(mContext, 260), DisplayUtil.dip2px(mContext, 260),"这首歌像黄昏下一个人在街道漫步，自在怡然","-来自Gyk的评论-"));
        list.add(cardView5);


        CardView cardView6 = new CardView();
        cardView6.setSlide(false);
        cardView6.setFinishSlide(false);
        cardView6.setWidth(DisplayUtil.dip2px(mContext, 260));
        cardView6.setHeight(DisplayUtil.dip2px(mContext, 260));
        cardView6.setMultiple(1f);
        cardView6.setImageView(createImageView(DisplayUtil.dip2px(mContext, 260), DisplayUtil.dip2px(mContext, 260),"想打你的电话，磕磕绊绊地向你诉说我愚笨又软弱的心","-来自Gyk的评论-"));
        list.add(cardView6);


        CardView cardView7 = new CardView();
        cardView7.setSlide(false);
        cardView7.setFinishSlide(false);
        cardView7.setMultiple(1f);
        cardView7.setWidth(DisplayUtil.dip2px(mContext, 260));
        cardView7.setHeight(DisplayUtil.dip2px(mContext, 260));
        cardView7.setImageView(createImageView(DisplayUtil.dip2px(mContext, 260), DisplayUtil.dip2px(mContext, 260),"人都是三分钟热度，但你就是我的第181秒","-来自Gyk的评论-"));
        list.add(cardView7);


        CardView cardView4 = new CardView();
        cardView4.setSlide(false);
        cardView4.setFinishSlide(false);
        cardView4.setMultiple(1f);
        cardView4.setWidth(DisplayUtil.dip2px(mContext, 260));
        cardView4.setHeight(DisplayUtil.dip2px(mContext, 260));
        cardView4.setImageView(createImageView(DisplayUtil.dip2px(mContext, 260), DisplayUtil.dip2px(mContext, 260),"其实折磨你的，不是任何人的绝情，而是你一直心存幻想的期待","-来自Gyk的评论-"));
        list.add(cardView4);

        CardView cardView1 = new CardView();
        cardView1.setSlide(false);
        cardView1.setMultiple(1f);
        cardView1.setWidth(DisplayUtil.dip2px(mContext, 300));
        cardView1.setHeight(DisplayUtil.dip2px(mContext, 300));
        cardView1.setImageView(createImageView(DisplayUtil.dip2px(mContext, 300), DisplayUtil.dip2px(mContext, 300),"我想做你的男孩，你的巨人","-来自Gyk的评论-"));
        cardView1.setFinishSlide(false);
        list.add(cardView1);


        CardView cardView2 = new CardView();
        cardView2.setSlide(false);
        cardView2.setMultiple(1f);
        cardView2.setWidth(DisplayUtil.dip2px(mContext, 340));
        cardView2.setHeight(DisplayUtil.dip2px(mContext, 340));
        cardView2.setImageView(createImageView(DisplayUtil.dip2px(mContext, 340), DisplayUtil.dip2px(mContext, 340),"我对日落许愿，希望你永远在我身边","-来自Gyk的评论-"));
        cardView2.setFinishSlide(false);
        list.add(cardView2);


        /**
         * 添加view,view绘制顺序由addView()添加的顺序决定
         */
        for (int i = 0; i < list.size(); i++) {
            CardView mView = list.get(i);
            addView(mView.getImageView());
            setLayoutparams(mView.getImageView(), mView.getWidth(), mView.getHeight(), i);
        }
    }

    /**
     * 设置图片的参数（宽、高、透明度）
     *
     * @param view
     * @param width
     * @param height
     * @param position
     */
    private void setLayoutparams(ImageView view, int width, int height, int position) {
        ViewGroup.LayoutParams layoutParams = (ViewGroup.LayoutParams) view.getLayoutParams();
        layoutParams.width = width;
        layoutParams.height = height;
        view.setLayoutParams(layoutParams);
        if (position == list.size() - 1) {
            view.setAlpha(1f);
        } else if (position == list.size() - 2) {
            view.setAlpha(0.8f);

        } else if (position == list.size() - 3) {
            view.setAlpha(0.4f);
        } else {
            view.setAlpha(0f);
        }
    }

    /**
     * 创建view
     *
     * @param width
     * @param height
     * @return
     */
    private ImageView createImageView(int width, int height,String content,String bottom) {
        TextImageView imageView = new TextImageView(getContext());
        imageView.setImageResource(R.mipmap.slidecard);
        imageView.setText(content,bottom);
        return imageView;
    }

    /**
     * MotionEvent.ACTION_DOWN
     * 手指按下时触发
     */
    private void downSlideTouch() {
        for (int i = list.size() - 1; i >= 0; i--) {
            if (!list.get(i).isFinishSlide()) {
                position = i;
                if (position!=0){
                    ((TextImageView)list.get(position-1).getImageView()).setNewColor("#978e91","#b4b4b4");
                    if (position-2==list.size()-3){
                        ((TextImageView)list.get(position-2).getImageView()).setNewColor("#00000000","#00000000");
                    }
                }
                break;
            }
        }
        if (position == 0) {
            if (list.get(position).isFinishSlide()) {
                list.get(position).getImageView().setVisibility(GONE);
            }
        }
    }

    /**
     * MotionEvent.ACTION_MOVE
     *
     * @param ev 手指移动时调用
     *           意味当前正在操作中
     */
    private void slideTouch(MotionEvent ev) {
        if (ev.getX() > mInitX) {//向右移动
            if (0 < (ev.getX() - mInitX) && (ev.getX() - mInitX) < MINTOUCHVALUE) {
                list.get(position).getImageView().setRotation((ev.getX() - mInitX) / 60);
                mRotationAngle = (ev.getX() - mInitX) / 60;
            }
            list.get(position).getImageView().setTranslationX((int) (ev.getX() - mInitX));
            isRight = true;
        } else if (ev.getX() < mInitX) {//向左移动
            if (0 < (mInitX - ev.getX()) && (mInitX - ev.getX()) < MINTOUCHVALUE) {
                list.get(position).getImageView().setRotation(-(mInitX - ev.getX()) / 60);
                mRotationAngle = (-(mInitX - ev.getX()) / 60);
            }
            list.get(position).getImageView().setTranslationX(-(int) (mInitX - ev.getX()));
            isRight = false;
        }
    }


    /**
     * 动画依次向前推进动画效果
     * @param translationX
     */
    private void finshOperation(int translationX){
        if (position != 0) {//是否是最后一张卡片
            if (position - 1 >= 0) {//当前滑动卡片前边的第一张卡片
                ((TextImageView)list.get(position-1).getImageView()).setNewColor("#000000","#b4b4b4");//隐藏自定义TextImageView的图片
                AnimatorSet animatorSet = new AnimatorSet();
                ObjectAnimator scaleXAnimator = ObjectAnimator.ofFloat(list.get(position - 1).getImageView(), "scaleX", list.get(position - 1).getMultiple(), (float)DisplayUtil.dip2px(mContext,340)/(float)list.get(position-1).getWidth());
                ObjectAnimator scaleYAnimator = ObjectAnimator.ofFloat(list.get(position - 1).getImageView(), "scaleY", list.get(position - 1).getMultiple(), (float)DisplayUtil.dip2px(mContext,340)/(float)list.get(position-1).getHeight());
                ObjectAnimator alphaAnimator = ObjectAnimator.ofFloat(list.get(position - 1).getImageView(), "alpha", 0.8f, 1f);
                ObjectAnimator valueAnimator = ObjectAnimator.ofFloat(list.get(position).getImageView(), "translationX", translationX);
                if (list.get(position - 1).getHeight() == DisplayUtil.dip2px(mContext, 260)) {
                    ObjectAnimator valueAnimatory = ObjectAnimator.ofFloat(list.get(position - 1).getImageView(), "translationY", 240);
                    animatorSet.playTogether(valueAnimator, valueAnimatory, scaleXAnimator, scaleYAnimator, alphaAnimator);
                } else {
                    ObjectAnimator valueAnimatory = ObjectAnimator.ofFloat(list.get(position - 1).getImageView(), "translationY", DisplayUtil.dip2px(mContext,340)-list.get(position-1).getHeight());
                    animatorSet.playTogether(valueAnimator, valueAnimatory, scaleXAnimator, scaleYAnimator, alphaAnimator);
                }
                animatorSet.setDuration(ANIMATORDURATION);
                animatorSet.start();
                list.get(position - 1).setMultiple((float) DisplayUtil.dip2px(mContext, 340) / (float) list.get(position - 1).getWidth());
            }
            if (position - 2 >= 0) {//当前滑动卡片前边的第二张图片
                if (position-3>=0){
                    ((TextImageView)list.get(position-3).getImageView()).setNewColor("#00000000","#00000000");
                }
                ObjectAnimator valueAnimatory = ObjectAnimator.ofFloat(list.get(position - 2).getImageView(), "translationY", DisplayUtil.dip2px(mContext, 300) - list.get(position - 2).getHeight());
                ObjectAnimator scaleXAnimator = ObjectAnimator.ofFloat(list.get(position - 2).getImageView(), "scaleX", list.get(position - 2).getMultiple(), (float) DisplayUtil.dip2px(mContext, 300) / list.get(position - 2).getWidth());
                ObjectAnimator scaleYAnimator = ObjectAnimator.ofFloat(list.get(position - 2).getImageView(), "scaleY", list.get(position - 2).getMultiple(), (float) DisplayUtil.dip2px(mContext, 300) / list.get(position - 2).getHeight());
                ObjectAnimator alphaAnimator = ObjectAnimator.ofFloat(list.get(position - 2).getImageView(), "alpha", 0.4f, 0.8f);
                AnimatorSet animatorSet = new AnimatorSet();
                animatorSet.playTogether(scaleXAnimator, scaleYAnimator, valueAnimatory, alphaAnimator);
                animatorSet.setDuration(ANIMATORDURATION);
                animatorSet.start();
                list.get(position - 2).setMultiple((float) DisplayUtil.dip2px(mContext, 300) / list.get(position - 2).getWidth());
            }
            if (position - 3 >= 0) {//当前滑动卡片前边的第三张图片
                ObjectAnimator tYAnimator = ObjectAnimator.ofFloat(list.get(position - 3).getImageView(), "translationY", 60);
                ObjectAnimator alphaAnimator = ObjectAnimator.ofFloat(list.get(position - 3).getImageView(), "alpha", 0f, 0.4f);
                AnimatorSet animatorSet = new AnimatorSet();
                animatorSet.playTogether(tYAnimator, alphaAnimator);
                animatorSet.setDuration(ANIMATORDURATION);
                animatorSet.start();
            }
            list.get(position).setFinishSlide(true);
        }else {
            ObjectAnimator rotationAnimator = ObjectAnimator.ofFloat(list.get(position).getImageView(), "rotation", 0, mRotationAngle);
            ObjectAnimator valueAnimator = ObjectAnimator.ofFloat(list.get(position).getImageView(), "translationX", translationX);
            AnimatorSet set = new AnimatorSet();
            set.playTogether(rotationAnimator, valueAnimator);
            set.setDuration(ANIMATORDURATION);
            set.start();
            list.get(position).setFinishSlide(true);
        }
    }

    /**
     * MotionEvent.ACTION_UP
     *
     * @param ev 手指抬起时调用
     *           意味当前操作已完毕
     */
    private void finshTouchSlide(MotionEvent ev) {
        if (isRight) {//右滑
            if ((ev.getX() - mInitX) > MINTOUCHVALUE) {//右滑超过阈值
                finshOperation(mScreenWidth);
            }else {//右滑未超过阈值
                ObjectAnimator rotationAnimator = ObjectAnimator.ofFloat(list.get(position).getImageView(), "rotation", mRotationAngle, 0);
                ObjectAnimator valueAnimator = ObjectAnimator.ofFloat(list.get(position).getImageView(), "translationX", 0);
                AnimatorSet set = new AnimatorSet();
                set.playTogether(rotationAnimator, valueAnimator);
                set.setDuration(ANIMATORDURATION);
                set.start();
                list.get(position).setFinishSlide(false);
            }
        } else {//左滑
            if (mInitX - ev.getX() > MINTOUCHVALUE) {//左滑超过阈值
                 finshOperation(-mScreenWidth);
            } else {//左滑未超过阈值
                ObjectAnimator rotationAnimator = ObjectAnimator.ofFloat(list.get(position).getImageView(), "rotation", mRotationAngle, 0);
                ObjectAnimator valueAnimator = ObjectAnimator.ofFloat(list.get(position).getImageView(), "translationX", 0);
                AnimatorSet set = new AnimatorSet();
                set.playTogether(rotationAnimator, valueAnimator);
                set.setDuration(ANIMATORDURATION);
                set.start();
                list.get(position).setFinishSlide(false);
            }
        }
        mInitX = 0;
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                mInitX = ev.getX();
                downSlideTouch();
                break;
            case MotionEvent.ACTION_MOVE:
                slideTouch(ev);
                break;
            case MotionEvent.ACTION_UP:
                finshTouchSlide(ev);
                break;
        }
        return true;
    }
}


//
//      if (ev.getX() > mInitX) {//向右移动
//              if (0 < (ev.getX() - mInitX) && (ev.getX() - mInitX) < 600) {
//        mImg1.setRotation((ev.getX() - mInitX) / 60);
//        mRotationAngle = (ev.getX() - mInitX) / 60;
//        }
//        mImg1.setTranslationX((int) (ev.getX() - mInitX));
//        isRight = true;
//        } else if (ev.getX() < mInitX) {//向左移动
//        if (0 < (mInitX - ev.getX()) && (mInitX - ev.getX()) < 600) {
//        mImg1.setRotation(-(mInitX - ev.getX()) / 60);
//        mRotationAngle = (-(mInitX- ev.getX()) / 60);
//        }
//        mImg1.setTranslationX(-(int) (mInitX - ev.getX()));
//        isRight = false;
//        }

//   if (isRight) {
//           if ((ev.getX() - mInitX) > 600) {
//           ObjectAnimator valueAnimator = ObjectAnimator.ofFloat(mImg1, "translationX", mScreenWidth);
//           valueAnimator.setDuration(500);
//           valueAnimator.start();
//           } else {
//           ObjectAnimator rotationAnimator = ObjectAnimator.ofFloat(mImg1, "rotation", mRotationAngle, 0);
//           ObjectAnimator valueAnimator = ObjectAnimator.ofFloat(mImg1, "translationX", 0);
//           AnimatorSet set = new AnimatorSet();
//           set.playTogether(rotationAnimator, valueAnimator);
//           set.setDuration(500);
//           set.start();
//           }
//           } else {
//           if (mInitX - ev.getX() > 600) {
//           ObjectAnimator valueAnimator = ObjectAnimator.ofFloat(mImg1, "translationX", -(mScreenWidth));
//           valueAnimator.setDuration(500);
//           valueAnimator.start();
//           } else {
//           ObjectAnimator rotationAnimator = ObjectAnimator.ofFloat(mImg1, "rotation", mRotationAngle, 0);
//           ObjectAnimator valueAnimator = ObjectAnimator.ofFloat(mImg1, "translationX", 0);
//           AnimatorSet set = new AnimatorSet();
//           set.playTogether(rotationAnimator, valueAnimator);
//           set.setDuration(500);
//           set.start();
//           }
//           }
//           mInitX = 0;